'use strict';
if ( ! ''.trim || ! document.querySelectorAll || ! document.querySelectorAll.bind || ! Object.keys )
   document.getElementById('msg_upgrade_browser').style.display = 'block';

var _ = document.querySelectorAll.bind( document );
var make = document.createElement.bind( document );

var shdic={};

shdic.log = (function ()
{
    var _debug = true;
    return {
        debug:function(m){
        	try{
        		if(_debug){
        			alert(m);
        		}
        	}catch(e){};
        	return false;
        }
    };

})();	//shdic.log end.

shdic.pub = (function ()
{
    return {
        nr: function (msg)
        {
            var tt = '';
            if(msg) tt=msg;
            alert('Not Ready! '+tt);
            return ;

        },drop_last:function(s,n){
        	if(!n) n=1;
        	return s.substring(0,s.length-n);

        },cint:function(n){
        	var t=0;
        	try{
        		t=parseInt(n);        		
        	}catch(e){};        	
        	return t;
        }
    };

})();	//shdic.pub end.

/**
 * 对用户在TextArea中输入的数据进行过滤，把< -> <等操作，以及逆向操作
 */
shdic.htmlFilter = (function ()
{
    /**
     * 转化textarea中的空格为$nbsp;
     * \n转化为<br/>
     * @private
     */
    function _transSpace(data)
    {
        return data.replace(/\n/g, "<br/>").replace(/\s/g, " ");
    };
    /**
     * 转化所有尖括号
     * @private
     */
    function _transBrace(data)
    {
        return data.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    };
    function _resumeSpace(data)
    {
        return data.replace(/ /g, " ").replace(/<br\s*\/>/ig, "\n");
    };
    function _resumeBrace(data)
    {
        return data.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
    };

    return {
        txt2Html: function (data)
        {
            return _transSpace(_transBrace(data));

        }, html2Txt: function (data)
        {
            return _resumeSpace(_resumeBrace(data));
        }
    };

})();


function str2json(data){
	if(data==undefined) return null;
	try{
		var dataObj=eval("("+data+")");//转换为json对象
		return dataObj;
	}catch(e){		
		alert('Error ! in function str2json !');
		alert(e.name + ": " + e.message);
		if(data.length>0) alert(data);
		else if (data.length<1) alert("[data] is empty!");
		console.log(data);
		return null;
	}   
}

function getJsonAtt(json,att){
	return getAtt(json,att);
   // if(!json) return '';
   // var ret = '';
   // $.each(json,function(idx,item){ 
   //    if(idx==att){
   //       ret = item;
   //       // break;
   //       return false;
   //    }
   // });
   // return ret;
}

function getAtt(json,att){
	if(!json) return '';
	var ret = '';
	for (var idx in json){
		var item=json[idx];
		if(idx==att){
			ret = item;
			// break;
			// return false;
		}
	}
	return ret;
}

function deepClone(obj){
   function Clone(){};
   Clone.prototype = obj;
   var o = new Clone();
   for(var a in o){
      if(typeof o[a] == "object") {
         o[a] = deepClone(o[a]);
      }
   }
   return o;
}


function errMsg(msg,t){
	if(!t){
    	t=1500;
    }else if(t<10){
  		t=t*1000;
    }
	$("#div_errormsg").show();
	$("#errormsg").html(msg).show(300).delay(t).hide(300); 
	// alert("aa");
	setTimeout(function(){
		$("#div_errormsg").hide();
	},+t+600);
	
}


// *-*-*-*-*-*-*-*-*-*-*-*-* for this app code end


var appcan={};
appcan.window=(function ()
{
    function open(name,data,aniId,type,dataType,width,height,animDuration)
    {
        return data.replace(/\n/g, "<br/>").replace(/\s/g, " ");
    };
    return window;

})();


function winOpen(id,url) {
	// appcan.window.open(name,data,aniId,type,dataType,width,height,animDuration)
	appcan.window.open(id,url,2,4);
}

function openPopWin(id,url){
	// appcan.window.openPopover(name,dataType,url,data,left,top,width,height,fontSize,type,bottomMargin)
	appcan.window.openPopover(id,0,url);
}

function winCls(name){
	if(name){
		appcan.frame.close(name)
	}else{
		appcan.window.close(1,500);	
	}	
}

function $$(id){
	return document.getElementById(id);
}

function db_op_msg(msg){
	try{
		var tt = document.getElementById('div_db_op_msg');
		var ss='';
		if(tt){
			ss = tt.innerHTML;
			tt.innerHTML=ss+'<br/>'+msg;
		}else{
			alert(msg);
		}
	}catch(e){
		alert(e.name + ": " + e.message);
	};
		
}

function clear_db_op_msg(){
	var tt = document.getElementById('div_db_op_msg');
	var ss='';
	if(tt && tt.innerHTML){
		tt.innerHTML='';
	}else{
		alert('Error ! [div_db_op_msg] Not found !');
	}
}

function openNewWin(inWndName,html,inAniID,f,time)
{
	if (inAniID) {
		uexWindow.open(inWndName,'0',html,inAniID,'','',(f)?f:4,time?time:250);
	}
	else {
		uexWindow.open(inWndName, '0', html, '2', '', '', (f) ? f : 4);
	}
}

/*
用uexXmlHttpMgr封装AJAX方法
主要解决uexXmlHttpMgr同时多次发起时，onData参数会被覆盖的问题（懂的人会懂的，不明白的人的话忽略 直接用即可。）
*/
window.AJAX = {
	callBack : {},index : 1,
	get : function(url,succCall,errCall,timeout){
		var id = this.index++;
		this.callBack[id] = [succCall,errCall];
		uexXmlHttpMgr.open(id,'get',url,(timeout||0));
		this._send(id);
	},
	post : function(url,data,succCall,errCall,timeout){
		var id = this.index++;
		this.callBack[id] = [succCall,errCall];
		uexXmlHttpMgr.open(id,'post',url,(timeout||0));
		if(data){
			for(var k in data){
				uexXmlHttpMgr.setPostData(id,0,k,data[k]);
			}
		}
		this._send(id);
	},
	_send : function(id){
		uexXmlHttpMgr.onData = this.onData;
		uexXmlHttpMgr.send(id);
	},
	onData : function(inOpCode,inStatus,inResult){
		var that=AJAX,callBack = that.callBack[inOpCode]||[];
		if(inStatus==-1){
			callBack[1] && callBack[1]();
		}else if(inStatus==1){
			callBack[0] && callBack[0](inResult);	
		}
		//delete that.callBack[inOpCode];
	}
};


function get_server_root(){	
	var api_root='http://www.shdic.com';
	try{		
		var mode = appcan.locStorage.val('mode');
		if(mode && mode=='local_dev'){
			// api_root='http://192.168.191.1:9980/appidf738cydm44';
			var ip=ls_v('local_api_ip');
			if(!ip) ip = '192.168.191.1:9980/appidf738cydm44';			
			api_root = 'http://'+ip;
			// alert(api_root);
			autoClsMsg('DEBUG!!! api_root='+api_root);
		}
	}catch(e){};
	return api_root;	
}

function show_val(m,v) {
    if(v!=undefined && v!=''){
        return m+v;
    }
    return '';
}

function ls_v(n,d){
	if(!d) d='';
    return ls_get(n,d);
}

function ls_get(k,v){
	var tt = appcan.locStorage.val(k);
    if(tt){
        return tt;
    }
    if(v){
        return v;  
    }else{
        return '';    
    }
}
function ls_set(k,v){
	if(v){
		appcan.locStorage.setVal(k,v);
	}else{
		appcan.locStorage.setVal(k,'N/A');
	}
}
function ls_del(k){
	appcan.locStorage.remove(k);
}

function check_exp(kk){

	var token = ls_v('token',0);
	var uid = ls_v('uid',0);
	if (token && uid && token.length>9){
		//base check
	}else{
		autoClsMsg('登陆信息已经失效！#check_exp ,'+token+','+uid);
		ls_del('token');
		// appcan.window.close(1,500);
		return false;
	}


	var api_root=get_server_root();
	var api = api_root+'/apps/survival_camp_v1/index.php?c=api';
	var pc_url = api + '&a=player_info&token='+token+'&uid='+uid;
	pc_url = pc_url + '&seed='+Math.random();
	var ret=false;

	AJAX.get(pc_url,function(res2){
		//alert(res2); 
		// autoClsMsg('DEBUG!! #check_exp ,'+res2);
		$("#div_debug").html('DEBUG!! #check_exp ,'+res2);

		var tt=str2json(res2);
		if(tt && tt.err_code=='0'){
			var ttd = tt.data;
	     
			ret = true;
			//alert('exp'+ttd.exp);
			appcan.locStorage.setVal(kk,'ok');
		}else{
			alert('AJAX失败！#check_exp! '+res2);  
		}
	},function(){
		alert('AJAX失败！请检查网络是否畅通！#check_exp');  
	});
    //alert('func exit');
    ClsWait();
    return true;
}

function wait_ajax(op_key){
    if(ls_v(op_key)!='ok'){
    	$("#ajax_debug").append('#');
        setTimeout("wait_ajax('"+op_key+"')",100);
    }else{
        setTimeout('show_info()',100);
    }
}

var last_ajax_url=null;
var last_ajax_time=null;
var ajax_interval_time=9*1000;

// Dictionaries, used to populate select box or check for duplicate entries.
var ajax_op = /** @dict */ Object.create( null );
// if ( ! dict_list[ b ] ) dict_list[ b ] = 1; else ++dict_list[ b ];

function ajax_load(op_key,callBack){
	return ajaxApi(op_key,'',callBack);
}

function ajaxLoadDefaultCallBack(jsonObj){
    shdic.log.debug('in ajaxLoadDefaultCallBack()');
    var text = JSON.stringify(jsonObj);
    debug_log(text);
    
    var jd=jsonObj.data;
    var src = jd.msg;
    // alert(src);
    hotMsg(src);        
    // ClsWait();
};

function ajaxApi(op_key,data,callBack){
    
    var token = ls_v('token',0);
    var uid = ls_v('uid',0);
    if (token && uid && token.length>9){
        //base check
    }else{
    	// alert('登陆信息已经失效！');
    	autoClsMsg('登陆信息已经失效！#ajax_load ,'+token+','+uid);
    	ls_del('token');
	// appcan.window.close(1,500);
        return false;
    }

    appcan.locStorage.setVal(op_key,'wait');

    var api_root=get_server_root();
    var api = api_root+'/apps/survival_camp_v1/index.php?c=api';
    var pc_url = api + '&a='+op_key+'&token='+token+'&uid='+uid;

    //限制短时间内重复读取
    if(pc_url==last_ajax_url){        
        var now = new Date().getTime();
        var diffValue = now - last_ajax_time;
        if(diffValue<ajax_interval_time){
        	alert('刷新的太快了，休息几秒再试吧！');
			
			if(ajax_op[pc_url]){
        		var tt=ajax_op[pc_url];
        		if(callBack!=undefined){
					callBack(tt);
	        	}else{
	        		ajaxLoadDefaultCallBack(tt);
	        	}
	            ret = true;
	            appcan.locStorage.setVal(op_key,'ok');
	            $("#ajax_debug").append('');
        	}
			// ClsWait();
            return false;
        }
    }
    last_ajax_url=pc_url;
    last_ajax_time=now;

	if(data) pc_url = pc_url + data;

    var ret=false;

    AJAX.get(pc_url+'&seed='+Math.random(),function(res2){
        // alert(res2); 
        var tt=str2json(res2);
        if(tt && tt.err_code=='0'){
        	ajax_op[pc_url]=tt;
        	if(callBack!=undefined){
				callBack(tt);
        	}else{
        		ajaxLoadDefaultCallBack(tt);
        	}
            ret = true;
            appcan.locStorage.setVal(op_key,'ok');
            $("#ajax_debug").append('');
        }else{
        	alert('Error!!! '+res2);
        }
    },function(){
        alert('AJAX失败！请检查网络是否畅通！#'+op_key);  
    });
    //alert('func exit');
    ClsWait();
    return true;
}

function loadingWin(){
    uexWindow.toast(1,5,"正在加载...",1);
}

function waitWin(n){
	// uexWindow.toast(1,5,"正在加载...",0);	
	autoClsMsg("正在加载...",n);
}

function ClsWait(){
    uexWindow.closeToast();
}

var timeoutHandle=null;
function autoClsMsg(msg,t){
    // uexWindow.toast(1,5,msg,0);    
    if(!t){
    	t=1500;
    }else if(t<10){
  		t=t*1000;
    }
    $.Prompt(msg,t);
    if(timeoutHandle) clearTimeout(timeoutHandle);
    timeoutHandle=setTimeout('ClsWait()',t);
}


function hotMsg(src,t){
	$("#hot_msg").html(src);
	if(t){
		if(t<16) t=t*1000;
		setTimeout('resetHotMsg()',t);
	}else{
		setTimeout('resetHotMsg()',2000);	
	}	
}
function resetHotMsg(){
	$("#hot_msg").html('');
}

var isArray = function(obj) { 
	return Object.prototype.toString.call(obj) === '[object Array]'; 
}

function debug_log(text){
  try{
    var tt = ls_v('debug_mode');
    if(tt=='1'){
    	var tt=$("#div_debug");
    	if(tt.length>1) $("#div_debug").html(text).show();
    	var tt=$("#ajax_debug");
        if(tt.length>1) $("#ajax_debug").html(text).show();
    }else{
        $("#div_debug").hide();
        $("#ajax_debug").hide();
    }
  }catch(e){
  	console.log(text);
  };	
}

function makeTmpTable(jsonData,ud_desc,selector){
    var jd=jsonData;
    var src = '';
    var tr_att = ' height="50px"';
    src = '<table id="tmptable1" class="tmptable"><tbody>';
    src = src + '<tr'+tr_att+' class="head">';
    src = src + get_td_cell(' ','#' );
    var count=0;
    $.each(ud_desc,function(idx,item){ 
        src = src + get_td_cell(' ',item);
        count++;
    });
    src = src + '</tr>';
    if(selector){
        $(selector).html(src);    
    }    

    if(isArray(jd)){
        var i2=0;
        $.each(jd,function(idx,item){ 
            var tmp = item;
            i2 = i2+1;
            src = src + '<tr'+tr_att+' class="body">';
            src = src + get_td_cell('','#'+i2 );
            $.each(ud_desc,function(idx1,item1){ 
                var tt = getJsonAtt(tmp,idx1);
                src = src + get_td_cell(' ',tt);
            });
            src = src + '</tr>';
        });
    };
    
    if(selector){
        $(selector).html(src);    
    } 
    return src;
};

function get_td_cell(att,tit){
    if(!tit) tit='&nbsp;';
    return '<td'+att+'>'+tit+'</td>';
}

/******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ********/

shdic.sc={
    title:'survival camp',
    ver:1
};

/******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ********/

shdic.sc.html = (function ()
{
    var _op_att=function (onClickFunc)
    {
        //<div class='tit c-blu c-m1 uinn uc-b1' ontouchstart="zy_touch('btn-act')" onclick="closeTmpFram('tmp');">关闭</div>
        return ' ontouchstart="zy_touch(\'btn-act\')" onclick="'+onClickFunc+';"';
    };

    var _op_div=function (onClickFunc,tit)
    {
        //<div class='tit c-blu c-m1 uinn uc-b1' ontouchstart="zy_touch('btn-act')" onclick="closeTmpFram('tmp');">关闭</div>
        return '<div class=\'tit c-blu c-m1 uinn uc-b1\' '+_op_att(onClickFunc)+'>'+tit+'</div>';
    };

    var _td_cell=function (att,tit,opCallback)
    {
		if(!tit) tit='&nbsp;';
		if(opCallback!=undefined){
		    att = att + ' ' + _op_att(opCallback);
		}
		return '<td'+att+'>'+tit+'</td>';
    };

    return {
        get_td_cell: function (att,tit,opCallback)
        {
            return _td_cell(att,tit,opCallback);   

        },op_div: function (onClickFunc,tit)
        {
            //<div class='tit c-blu c-m1 uinn uc-b1' ontouchstart="zy_touch('btn-act')" onclick="closeTmpFram('tmp');">关闭</div>
            return _op_div(onClickFunc,tit);   

        },cint:function(n){
            var t=0;
            try{
                t=parseInt(n);              
            }catch(e){};            
            return t;
        }
,makeTmpTableOP:function(jsonData,ud_desc,p3,opTit,opFuncName)
{
	var jd=jsonData;
    var src = '';
    var tr_att = ' height="50px"';
    var count=0;
    src = '<table id="tmptable1" class="tmptable"><tbody>';
    src = src + '<tr'+tr_att+' class="head">';

  try{	
    src = src + _td_cell(' ','#' );    
    for (var idx in ud_desc){
        var item=ud_desc[idx];
        src = src + _td_cell(' ',item);
        count++;
    };
    src = src + '</tr>';

	var sub_desc=p3;
	var selector=p3;
	if(isArray(p3)){
		selector=false;
	}else{
		sub_desc=false;
	}

    // if(selector){
        // $(selector).html(src);
    // }

    if(isArray(jd)){
        var i2=0;
        for (var idx in jd){
            var item=jd[idx];
            var tmp = item;
            i2 = i2+1;
            src = src + '<tr'+tr_att+' class="body">';
            src = src + _td_cell('','#'+i2 );
            for (var idx1 in ud_desc){
                var item1=ud_desc[idx1];
                var tt = getAtt(tmp,idx1);
				var sub_d=getAtt(sub_desc,idx1);
                if(sub_d){
                    tt= getAtt(sub_d,tt);
                }

                if(opTit && idx1==opTit){
                    var idcode=0;
                    if(item.id){
                        idcode=item.id;
                    }
                    if(item.code){
                        idcode=item.code;
                    }
                    if(idcode){
                        // tt = tt + ' #'+shdic.sc.title+' v'+shdic.sc.ver;
                        src = src + _td_cell(' ',tt,opFuncName+'(\''+idcode+'\',\''+tt+'\')');
                    }else{
                        src = src + _td_cell(' ',tt,'alert(\'Miss ID or CODE !!! '+tt+'\')');
                    }
                    // src = src + _td_cell(' ',tt,'alert(\''+tt+'\')');
                }else{
                    src = src + _td_cell(' ',tt);
                }
            };
            src = src + '</tr>';
        };
    };
    
    // if(selector){
    //     $(selector).html(src);    
    // }
    
  }catch(e){};       
	return src;

}	//makeTmpTableOP end.

    };	//shdic.sc.html return end.

})();	//shdic.sc.html end.


/******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ******** 
******** ******** ******** ******** ******** ******** ******** ******** ********/

shdic.sc.itemOP=(function ()
{
    var _items_buff=[];

    var _can_food=function (onClickFunc)    //not ok
    {
        return 'Not ready!!!';
    };

	var _getItemById=function (id)
	{
		var jd=_items_buff;
		if(jd && isArray(jd) ){
			//
		}else{
		    alert('数据异常，请重新登陆后再操作！');
		    return false;
		}
		var opItem=null;
		try{
		    for (var idx in jd){
		        var item=jd[idx];
		        if(item && item.id){
		            if(item.id==id){
		                opItem = item;
		                break;
		            }
		        }
		    };
		}catch(e){alert('getItemById() Error!! '+e.name + ": " + e.message);};
		return opItem;
    };

    var _get_btn=function (item)
    {
        if(item.category==undefined){
            return false;
        }

        switch (+item.category) {
        case 1: 
            // alert("消耗品");
            // var tt=shdic.sc.html.op_div('aa','食用:'+item.title);
            // $('#opbar').html(tt);
            return _show_item_detail(item);
            break;

        case 2: 
            // alert("装备");
            return _show_item_detail_and_spare_parts(item);		//显示详情和备件（同类可替换的物品）
            break;

        case 3:
            // alert("武器");
            return _show_item_detail_and_spare_parts(item);
            break;

        default:
            // alert("other，无特别操作按钮！");
            // return false;
            return _show_item_detail(item);		//显示详细情况
        }

    };

	var _show_item_detail_and_spare_parts=function (item)
    {
        if(item.sub_category==undefined){
        	alert('Error! _show_item_detail_and_spare_parts()!');
            return false;
        }
        var info = '';
        
        info = info + "大类:"+item.category;
        info = info + ",小类:"+item.sub_category;
        
        alert(item.title+':'+info);
        
    };

    var _show_item_detail=function (item)
    {
        if(item.sub_category==undefined){
        	alert('Error! _show_item_detail()!');
            return false;
        }
        var info = '';
        switch (+item.sub_category) {
        case 1: 
            info = "消耗品-食物";
            break;

        case 2: 
            info="消耗品-饮料";
            break;

        case 3:
            info = "消耗品-医疗物品";
            break;

        case 4:
            info = "消耗品-弹药";
            break;

        default:
            info= "消耗品-other";
        }
        if(+item.category==1){
			alert(item.title+':'+info);
        }else{
        	alert(item.title+'详情 not ready!!');
        }        
    };

    var _get_cat1_btn=function (item)
    {
        if(item.sub_category==undefined){
            return false;
        }

        switch (+item.sub_category) {
        case 1: 
            alert("消耗品-食物");
            var tt=shdic.sc.html.op_div('aa','食用:'+item.title);
            break;

        case 2: 
            alert("消耗品-饮料");
            var tt=shdic.sc.html.op_div('aa','饮用:'+item.title);
            break;

        case 3:
            alert("消耗品-医疗物品");
            var tt=shdic.sc.html.op_div('aa','使用(医疗物品):'+item.title);
            break;

        case 4:
            alert("消耗品-弹药");
            var tt=shdic.sc.html.op_div('aa','使用(弹药):'+item.title);
            break;

        default:
            alert("消耗品-other");
        }
        $('#opbar').html(tt);
    };
    

    return {
        food: function (itemBuff,id)
        {
            return _can_food(itemBuff,id);

        },getBtn: function (item)
        {
            return _get_btn(item);

        },onClick: function (item)
        {
            var item = _getItemById(id);
			if(!item){
				alert('数据异常，请重新登陆后再操作！#2');
				return false;
			}
			return _get_btn(item);

        },init:function(jd){
        	_items_buff=[];
            try{
                if(jd.data){
                	jd=jd.date;
                }
                _items_buff=jd;
            }catch(e){};
            return jd;
        },getItemById:function(id)
		{
		    return _getItemById(id);
		}

    };  //shdic.sc.itemOp return end.

})();     //shdic.sc.itemOp end.


function opOnClickItem(id,tit){
    // alert('id='+id+',title='+tit);
    var item = shdic.sc.itemOP.getItemById(id);
    if(!item){
        alert('数据异常，请重新登陆后再操作！#2');
        return false;
    }
    shdic.sc.itemOP.getBtn(item);
};

